package com.sy.olddriver.dao.impl;

import com.sy.olddriver.dao.UserDao;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner runner = DBUtils.getRunner();

    @Override
    public Integer addUser(String name, String pwd, String phone) {
        try {
            return runner.update("insert into user(name,pwd,phone) values(?,?,?)", name, pwd, phone);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public List<String> getAllUserNames() {
        try {
            return runner.query("select name from user", new ColumnListHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<String> getAllPhones() {
        try {
            return runner.query("select phone from user", new ColumnListHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUserByName(String userName) {
        try {
            return runner.query("select * from user where name=?", new BeanHandler<>(User.class), userName);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
